<template>
  <!-- <h2>瀛湖</h2> -->
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{path:'/users'}">用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="yonghuliebiao.query"
            clearable
            @clear="getUserListInfo"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserListInfo"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUser">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="usersList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
        <el-table-column prop="role_name" label="身份"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop label="操作">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="aditUser(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeUser(scope.row.id)"
            ></el-button>
            <!-- 分配角色 -->
            <!-- <el-tooltip effect="dark" content="角色分配" placement="top"> -->
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              enterable="false"
              @click="settingUser(scope.row)"
            ></el-button>
            <!-- </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 页脚 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[1, 3, 5, 10]"
      :page-size="3"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!-- 添加用户的弹窗 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="40%" @close="closeAddUser">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <!-- 主体区域 -->
        <!-- 用户名： -->
        <el-form-item label="用户名：" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <!-- 密码： -->
        <el-form-item label="密码：" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <!-- 邮箱； -->
        <el-form-item label="邮箱；" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <!-- 电话： -->
        <el-form-item label="电话：" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="ADD">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户的弹窗 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="40%" @close="closeEditUser">
      <el-form :model="editForm" :rules="editRules" ref="editRuleRef" label-width="70px">
        <!-- 用户名 -->
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <!-- 手机号 -->
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="EDIT">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 给用户分配权限的弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="settingDialogVisible"
      width="50%"
      @close="closeSettingUser"
    >
      <p>当前的用户：{{this.userInfo.username}}</p>
      <p>当前的角色：{{this.userInfo.role_name}}</p>
      <p>
        <el-select v-model="userdeID" placeholder="请选择">
          <el-option
            v-for="item in rolesLists"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="settingDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUserRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
  </div>
</template>

<script>
export default {
  data() {
    //   验证手机
    var validatorPhone = (rule, value, callback) => {
      const regPhone = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/;
      if (regPhone.test(value)) {
        return callback();
      } else {
        callback(new Error("手机号格式不正确!"));
      }
    };
    // 验证邮箱
    const validatorEmail = (rule, value, callback) => {
      const regEmail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (regEmail.test(value)) {
        return callback();
      } else {
        callback(new Error("邮箱格式不正确!"));
      }
    };
    return {
      yonghuliebiao: {
        query: "",
        pagenum: "1",
        pagesize: "3"
      },
      total: 0,
      //获取的表单的列表
      usersList: [],
      // 当点击时更改弹窗是否显示
      addDialogVisible: false,
      editDialogVisible: false,
      // 添加用户的表单
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 修改用户的存值处
      editForm: {},
      // 添加用户表单的验证
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          { min: 1, max: 6, message: "长度在 1 到 6 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6 到 15 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: validatorEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入合法的电话号码", trigger: "blur" },
          {
            validator: validatorPhone,
            trigger: "blur"
          }
        ]
      },
      // 修改用户表单的验证
      editRules: {
        email: [
          { required: true, message: "请输入合法邮箱", trigger: "blur" },
          { validator: validatorEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入合法的电话号码", trigger: "blur" },
          {
            validator: validatorPhone,
            trigger: "blur"
          }
        ]
      },
      settingDialogVisible: false,
      // 当前行的数据
      userInfo: {},
      // 所有的角色列表
      rolesLists: {},
      // 当前角色的id
      userdeID: ""
    };
  },
  created() {
    this.getUserListInfo();
  },
  methods: {
    // 获取用户信息列表,渲染页面
    async getUserListInfo() {
      const { data: res } = await this.$http.get("users", {
        params: this.yonghuliebiao
      });
      //   console.log(res);
      // 若获取失败
      if (res.meta.status !== 200) {
        return console.log("获取用户列表失败！");
      }
      this.total = res.data.total;
      this.usersList = res.data.users;
      //   console.log("获取成功");
    },
    // 页面显示总数发生改变
    handleSizeChange(newSize) {
      this.yonghuliebiao.pagesize = newSize;
      this.getUserListInfo();
    },
    // 页码发生改变
    handleCurrentChange(newPage) {
      this.yonghuliebiao.pagenum = newPage;
      this.getUserListInfo();
    },
    // 修改用户状态,监听Switch状态
    async userStatusChange(userInfo) {
      // console.log(userInfo.mg_state)
      // 发起请求
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      //    console.log(res)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error("更新用户状态失败！");
      }
      this.$message.success("更新用户信息成功！");
    },
    // 点击添加用户弹出窗口
    addUser() {
      this.addDialogVisible = true;
    },
    // 关闭弹窗时，清空增加用户数据,重置表单
    closeAddUser() {
      this.$refs.addFormRef.resetFields();
    },
    // 关闭弹窗时，清空修改用户数据,重置表单
    closeEditUser() {
      this.$refs.editRuleRef.resetFields();
    },
    // 添加用户
    ADD() {
      // 预校验
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error("添加用户失败");
        // 发起添加请求
        const { data: res } = await this.$http.post("users", this.addForm);
        // console.log(res);
        if (res.meta.status !== 201)
          return this.$message.error("添加用户失败！");
        this.$message.success("添加用户成功！");
        this.getUserListInfo();
      });
      // 添加完，隐藏弹窗
      this.addDialogVisible = false;
    },
    // 修改用户信息，渲染到弹窗
    async aditUser(id) {
      const { data: res } = await this.$http.get("users/" + id);
      // console.log(res)
      if (res.meta.status !== 200)
        return this.$message.error("查询用户信息失败！");
      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    // 修改用户信息提交，并渲染到页面
    async EDIT() {
      // 预校验
      this.$refs.editRuleRef.validate(async valid => {
        if (!valid) return this.$message.error("修改用户信息失败");
        const { data: res } = await this.$http.put(
          "users/" + this.editForm.id,
          { email: this.editForm.email, mobile: this.editForm.mobile }
        );
        if (res.meta.status !== 200)
          return this.$message.error("修改用户信息失败！");
        this.$message.success("添加用户信息成功");
        // 重新渲染页面
        this.getUserListInfo();
        // 关闭窗口
        this.editDialogVisible = false;
      });
    },
    // 根据ID删除用户
    async removeUser(id) {
      const res = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      // console.log(res);
      // 若点击按钮获取的是 cancel 说明没删除
      // 若点击按钮获取的是 confirm 说明删除
      if (res != "confirm") return this.$message.info("删除失败");
      const { data: ret } = await this.$http.delete("users/" + id);
      if (ret.meta.status !== 200) return this.$message.info("删除失败");
      this.$message.success("删除成功！");
      if (this.total % this.yonghuliebiao.pagesize === 1) {
        this.yonghuliebiao.pagenum--;
      }
      this.getUserListInfo();
    },
    // 给用户分配权限
    async settingUser(userInfo) {
      // 获取表格中数据
      this.userInfo = userInfo;
      // console.log(this.userInfo);
      // 获取所有的角色列表
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) return;
      this.rolesLists = res.data;
      this.settingDialogVisible = true;
    },
    // 保存当前选中的角色
    async saveUserRoles() {
      if (!this.userdeID) return this.$message.error("请选择角色！");
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.userdeID
        }
      );
      if (res.meta.status !== 200)
        return this.$message.error("配置用户角色失败!");
      this.$message.success("配置用户角色成功！");
      this.getUserListInfo();
      this.settingDialogVisible = false;
    },
    // 关闭按钮重置表单
    closeSettingUser() {
      (this.userInfo = ""), (this.userdeID = "");
    }
  }
};
</script>

<style lang='less' scoped>
.el-pagination {
  margin-top: 15px;
}
</style>